package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


//日志的切面:执行某个操作,添加日志
public class SystemLogAspect {

    @Autowired
    private ISystemLogService systemLogService;

    public void write(JoinPoint jp) throws JsonProcessingException {

        if (jp.getTarget() instanceof ISystemLogService) {
            return;
        }

        SystemLog log = new SystemLog();

        log.setOptime(new Date());

        log.setOpuser((Employee) SecurityUtils.getSubject().getPrincipal());

        //当前执行方法
        log.setFunction(jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
        //当前执行方法的参数
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));

        //获取IP
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.setOpip(request.getRemoteAddr());

        systemLogService.save(log);
    }
}
